from drf_spectacular.utils import extend_schema
from rest_framework import status
from rest_framework.decorators import action

from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from utils.autoschema import AutoDocSchema
from utils.decorators import error_response, request_data
from utils.pagination import PageLimitOffsetPagination

import backend.cews.services.DepotService as DepotService
from backend.cews.models import StockItem, Parts
from django.db.models import Q

from .serializers import DepotCarPartsSerailizer, StockItemSerializer, PartsWithFitmentSerializers
from rest_framework.pagination import LimitOffsetPagination




class DepotViewSet(
    # RetrieveModelMixin,
    # ListModelMixin,
    # UpdateModelMixin,
    GenericViewSet,
    # CreateModelMixin
):
    serializer_class = StockItemSerializer
    queryset = StockItem.objects.filter(deleted=False)
    pagination_class = LimitOffsetPagination
    pagination_class_page = PageLimitOffsetPagination

    @extend_schema(
        responses={200: DepotCarPartsSerailizer()},
    )
    @action(
        detail=False, methods=["POST"],
        url_name="get_parts_from_car", schema=AutoDocSchema()
    )
    @request_data(keys=["car"])
    @error_response()
    def get_parts_from_car(
        self,
        request,
        car
    ):
        '''
        desc: Get parts from car.
        json:
            car: string
        '''
        return Response(
            status=status.HTTP_200_OK,
            # data=DepotCarPartsSerailizer(
            #     DepotService.get_parts_from_car(car=car),
            #     many=True
            # ).data
                data=DepotService.get_parts_from_car(car=car),
        )

    @action(
        detail=False, methods=["POST"],
        url_name="fitment", schema=AutoDocSchema()
    )
    @request_data(keys=[
        "parent_stock_code",
        "parent_serial_no",
        "new_car",
    ], types={"parent_stock_code": str, "parent_serial_no": str, "new_car": str})
    @error_response()
    def fitment(
        self,
        request,
        parent_stock_code,
        parent_serial_no,
        new_car
    ):
        '''
        desc: Fitment for depot.
        json:
            parent_stock_code: string
            parent_serial_no: string
            new_car: string
        '''
        response = {
            "code": 0,
            "message": "Fitment failed."
        }

        if parent_serial_no == "" or parent_stock_code == "":
            response["message"] = "Serial no or stock code is empty."
            return Response(status=status.HTTP_400_BAD_REQUEST, data=response)

        reuslt = DepotService.fitment(
            parent_stock_code,
            parent_serial_no,
            new_car,
            request.user.username
        )

        if reuslt:
            response = {
                "code": 1,
                "message": "Fitment success."
            }

        return Response(status=status.HTTP_200_OK, data=response)

    @action(
        detail=False, methods=["POST"],
        url_name="search_parts_fitment", schema=AutoDocSchema()
    )
    @request_data(keys=["stock_code", "serial_no"], types={"stock_code": str, "serial_no": str})
    @error_response()
    def search_parts_fitment(
        self,
        request,
        stock_code,
        serial_no
    ):
        query = Q()
        if stock_code:
            query &= Q(stock_code__contains=stock_code)
        if serial_no:
            query &= Q(serial_no__contains=serial_no)

        # 分页版本
        # queryset = Parts.objects.all().filter(deleted=False).filter(query)
        # paginator  = self.pagination_class()
        # result = paginator.paginate_queryset(queryset, request) 

        # serializer=PartsWithFitmentSerializers(result,many=True)
        # return paginator.get_paginated_response(serializer.data)

        queryset = Parts.objects.all().filter(deleted=False).filter(query)

        serializer=PartsWithFitmentSerializers(queryset,many=True)
        return Response(status=200, data={"results":serializer.data})


    @action(
        detail=False, methods=["POST"],
        url_name="search_parts_fitment_paging", schema=AutoDocSchema()
    )
    @request_data(keys=["stock_code", "serial_no"], types={"stock_code": str, "serial_no": str})
    @error_response()
    def search_parts_fitment_paging(
        self,
        request,
        stock_code,
        serial_no
    ):
        query = Q()
        if stock_code:
            query &= Q(stock_code=stock_code)
        if serial_no:
            query &= Q(serial_no=serial_no)
        queryset = Parts.objects.all().filter(deleted=False).filter(query)
        paginator  = self.pagination_class_page()
        result = paginator.paginate_queryset(queryset, request) 

        serializer=PartsWithFitmentSerializers(result,many=True)
        return paginator.get_paginated_response(serializer.data)


    @action(
        detail=False, methods=["POST"],
        url_name="get_parts_from_parent",
        url_path="get_parts_from_parent",
          schema=AutoDocSchema()
    )
    @request_data(keys=["serial_no","stock_code"])
    @error_response()
    def get_parts_from_parent_api(
        self,
        request,
        serial_no,
        stock_code
    ):
        '''
        desc: Get parts from car.
        json:
            car: string
        '''
        return Response(
            status=status.HTTP_200_OK,
            # data=DepotCarPartsSerailizer(
            #     DepotService.get_parts_from_car(car=car),
            #     many=True
            # ).data
            data=DepotService.get_parts_from_parent(serial_no, stock_code)[0],
        )
